package com.yxhl.zoume.utils;

import android.util.Base64;

import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class RSA {

    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    private static final String KEY_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDklIQj5pGDEDQD/Wb+annY5v2sjLGwKEK3aLrFMGRP5f0M8y+rZCzTsL4G3rCVHcfb0JClQJI9gcPyen63fa3gsBmIWEJjB0x+3mIlM2weuzNORkdo+Te8f/DOaD1XuJRvuQnZ40uSP7w0sH2tFMhAVGPF2L4rLOiJ1F6zo4GqrQIDAQAB";

    public static String encryptWithRSA(String plainData) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(KEY_PUBLIC.getBytes(), Base64.DEFAULT));
            Key publicKey = keyFactory.generatePublic(keySpec);

            final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] cipherText = cipher.doFinal(plainData.getBytes("UTF-8"));
            // 必须先encode成 byte[]，再转成encodeToString，否则服务器解密会失败

            return Base64.encodeToString(cipherText, Base64.DEFAULT);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
